package com.mmc.delay.container;
import com.mmc.delay.bean.DeadJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;

import java.util.Set;

import static com.mmc.delay.constants.RedisKeyConstants.REDIS_DEAD_LETTER_KEY;

/**
 * 死信队列
 */
public class DeadLetterSet {

    private RedisTemplate redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(DeadLetterSet.class);

    public DeadLetterSet(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private BoundZSetOperations getBucket(String topic) {
        return redisTemplate.boundZSetOps(REDIS_DEAD_LETTER_KEY.concat(topic));
    }

    public void addDeadLetterQueue(DeadJob job){
        logger.info("任务移入死信队列,job:{}",job.toString());
        getBucket(job.getTopic()).add(job,job.getCreateTime());
    }

    public Set<ZSetOperations.TypedTuple> range(String topic, Long start, Long end){
        return getBucket(topic).rangeWithScores(start,end);
    }


    public Long totalNum(String topic){
        return getBucket(topic).size();
    }

    public Long removeDeadJob(DeadJob deadJob){
        return getBucket(deadJob.getTopic()).remove(deadJob);
    }

}
